<?php
declare(strict_types=1);
namespace app\api\controller;

use app\common\model\Admin;
use app\common\model\MpSubscribe;
use app\common\model\Qrcode;
use app\common\model\Third;
use app\common\model\QrcodeScan;
use think\annotation\route\Get;
use think\annotation\route\Group;
use think\annotation\route\Route;
use app\common\model\User;

#[Group("mpapp")]
class Mpapp extends Api{
    protected $noNeedLogin = ['*'];

    protected $config=[];

    const PAGE=[
        //首页
        'index'=>'/pages/index/index',
        //绑定用户
        'binduser'=>'/pages/index/index',
        //NEXT页
        'next'=>'/pages/index/next',
    ];

    protected function _initialize()
    {
        parent::_initialize();
        $this->config=[
            'appid'=>site_config("uniapp.mpapp_id"),
            'appsecret'=>site_config("uniapp.mpapp_secret"),
            'token'=>site_config("uniapp.mpapp_token"),
            'encodingaeskey'=>site_config("uniapp.mpapp_aeskey")
        ];
    }
    /**
     * 发起授权
     */
    #[Get('connect')]
    public function connect()
    {
        if($this->auth->id){
            return $this->gourl();
        }else{
            $arr=$this->request->get();
            if(count($arr)>0){
                $str='';
                foreach ($arr as $k=>$v){
                    $str.=$k.'='.$v.'&';
                }
                $str=substr($str,0,strlen($str)-1);
                $callback=$this->request->domain().'/api/mpapp/callback?'.$str;
            }else{
                $callback=$this->request->domain().'/api/mpapp/callback';
            }
            $wechat = new \WeChat\Oauth($this->config);
            // 执行操作
            $result = $wechat->getOauthRedirect($callback, '', 'snsapi_userinfo');
            return redirect($result);
        }
    }

    /**
     * 授权回调
     */
    #[Get('callback')]
    public function callback()
    {
        // 授权成功后的回调
        $wechat = new \WeChat\Oauth($this->config);
        $result = $wechat->getOauthAccessToken();
        $userinfo = $wechat->getUserInfo($result['access_token'],$result['openid']);
        $result['nickname']=$userinfo['nickname'];
        $result['avatar']=$userinfo['headimgurl'];
        //判断是否启用账号绑定
        $third=Third::connect('mpapp', $result);
        $this->auth->loginByThirdPlatform(Third::PLATFORM('微信公众号'),$third);
        return $this->gourl();
    }

    private function gourl()
    {
        $arr=$this->request->get();
        $action=$arr['action'];
        unset($arr['action']);
        unset($arr['code']);
        unset($arr['state']);
        $query='&'.http_build_query($arr);
        $url=request()->domain().'/h5/#'.self::PAGE[$action].'?token='.$this->auth->getToken().$query;
        return redirect($url);
    }

    /**
     * 创建菜单
     */
    #[Get('menu')]
    public function menu()
    {
        $this->error('请删除这行代码后重试');
        $menu = new \WeChat\Menu($this->config);
        $json=array('button'=>[
            //跳转到公众号页面
            [
                "name"=>"首页",
                "url"=>$this->request->domain()."/h5/#/pages/index/index",
                "type"=>"view",
            ],
            //跳转到小程序页面
            [
                "name"=>"列表",
                "type"=>"miniprogram",
                "appid"=>site_config("uniapp.miniapp_id"),
                "pagepath"=>"pages/index/list",
            ],
            //二级页面
            [
                "name"=>"我的",
                "sub_button"=>[
                    //先登陆，再跳转到指定页面
                    [
                        "name"=>"我的余额",
                        "url"=>$this->request->domain()."api/mpapp/connect?action=101",
                        "type"=>"view",
                    ],
                    [
                        "name"=>"其他菜单",
                        "type"=>"click",
                        "key"=>"V1001_GOOD",
                    ],
                ]
            ]
        ]);
        // 执行创建菜单
        $menu->create($json);
        $this->success('创建菜单成功');
    }

    /**
     * 公众号事件接收方法
     */
    #[Route('POST,GET','event')]
    public function event()
    {
        $api = new \WeChat\Receive($this->config);
        $msgtype=$api->getMsgType();
        if($msgtype=='text'){
            $api->text('尊敬客户您好，感谢您使用【'.site_config("basic.sitename").'】公众号！')->reply();
            return;
        }
        if($msgtype=='event'){
            $message = $api->getReceive();
            event('write_log','微信消息:'.json_encode($message));
            $event = $message['Event'];
            $eventkey = isset($message['EventKey'])? $message['EventKey'] : '';
            $openid=$message['FromUserName'];
            switch ($event) {
                //添加关注
                case 'subscribe':
                    $user = new \WeChat\User($this->config);
                    $userinfo=$user->getUserInfo($openid);
                    $unionid=isset($userinfo['unionid'])?$userinfo['unionid'] : '';
                    //记录关注
                    MpSubscribe::create([
                        'openid'=>$openid,
                        'unionid'=>$unionid,
                    ]);
                    //普通关注
                    if(is_array($eventkey)){
                        $api->text('尊敬客户您好，感谢您使用【'.site_config("basic.sitename").'】公众号！')->reply();
                        return;
                    }
                    //扫码关注
                    if(strpos($eventkey,'qrscene_')===0){
                        $eventkey=substr($eventkey,8);
                        $resp=$this->scanQrcode($openid,$unionid,$eventkey);
                        $api->text($resp)->reply();
                        return;
                    }
                //取消关注
                case 'unsubscribe':
                    MpSubscribe::where(['openid'=>$openid])->delete();
                    return;
                //扫二维码
                case 'SCAN':
                    $user = new \WeChat\User($this->config);
                    $userinfo=$user->getUserInfo($openid);
                    $unionid=isset($userinfo['unionid'])?$userinfo['unionid'] : '';
                    $resp=$this->scanQrcode($openid,$unionid,$eventkey);
                    $api->text($resp)->reply();
                    return;
                //跳转链接
                case 'VIEW':
            }
        }
    }

    /**
     * 扫码回调事件
     */
    private function scanQrcode($openid,$unionid,$qrcode_id)
    {
        $qrcode=Qrcode::find($qrcode_id);
        if(!$qrcode){
            return '尊敬客户您好，感谢您使用【'.site_config("basic.sitename").'】公众号！';
        }
        //记录扫码
        $scan=QrcodeScan::where(['openid'=>$openid,'qrcode_id'=>$qrcode->id])->find();
        if(!$scan){
            //生成的扫码记录表，可以在用户注册时，查询该表从而绑定推荐人
            QrcodeScan::create([
                'openid'=>$openid,
                'unionid'=>$unionid,
                'qrcode_id'=>$qrcode->id,
                'foreign_key'=>$qrcode->foreign_key,
                'type'=>$qrcode->type,
            ]);
        }
        //根据业务场景返回不同的消息
        switch ($qrcode->type){
            case 'backend-login':
                $third=Third::where(['platform'=>Third::PLATFORM('微信公众号'),'openid'=>$openid])->find();
                if(!$third){
                    return '您的微信没有绑定管理员，登陆失败！';
                }
                $admin=Admin::where(['third_id'=>$third->id])->find();
                if(!$admin){
                    return '您的微信没有绑定管理员，登陆失败！';
                }
                if($admin->status=='hidden'){
                    return '管理员已经被禁止，登陆失败！';
                }
                return '登陆成功！';
            case 'bind-third-user':
                $path=$this->request->domain()."/api/mpapp/connect?action=binduser";
                $end="<a href=\"{$path}\">👉👉点击这里授权👈️👈️</a>";
                return "您正在使用微信扫码授权获取您的微信头像、昵称\n\n{$end}";
            case 'toker':
                $user=User::find($qrcode->foreign_key);
                return '尊敬客户您好，您的好友'.$user->nickname.'推荐您使用【'.site_config("basic.sitename").'】公众号！';
        }
    }
}